﻿using BCCommon;
using BCEntity.OA.BusinessFlowPushRecord;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace BCData.OA.BusinessFlowPushRecord
{
    /// <summary>
    /// OA系统业务流推进记录
    /// </summary>
	public class BusinessFlowPushRecordData : IBusinessFlowPushRecordData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM OA_BusinessFlowPushRecord";
        private const string QUERY = @"SELECT BusinessFlowPushRecordId,BusinessFlowModelCode,ReferenceNo,RelatedReferenceNo,IsPushed,IsPushFailed,IsClosed,PushTime,PushCount,FailCount,CreateTime,PushFailRemark
                                        FROM OA_BusinessFlowPushRecord";
        public BusinessFlowPushRecordData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public async Task<bool> Exists(long businessFlowPushRecordId)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowPushRecordId=?BusinessFlowPushRecordId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowPushRecordId", businessFlowPushRecordId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> Exists(string businessFlowModelCode, string referenceNo)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowModelCode=?BusinessFlowModelCode AND ReferenceNo=?ReferenceNo AND IsPushed=0 AND IsClosed=0 LIMIT 1", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelCode", businessFlowModelCode?.Trim(), DbType.AnsiString);
            parameters.Add("?ReferenceNo", referenceNo?.Trim(), DbType.AnsiString);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<BusinessFlowPushRecordEntity> Add(BusinessFlowPushRecordEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("OA_BusinessFlowPushRecord", new string[] { "BusinessFlowModelCode", "ReferenceNo", "RelatedReferenceNo" });
            sql = string.Format("{0} {1} WHERE BusinessFlowPushRecordId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelCode", entity.BusinessFlowModelCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ReferenceNo", entity.ReferenceNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?RelatedReferenceNo", entity.RelatedReferenceNo?.Trim(), DbType.AnsiString, size: 50);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<BusinessFlowPushRecordEntity>(sql, parameters, databaseContext.Transaction);

        }

        public async Task<BusinessFlowPushRecordEntity> Update(BusinessFlowPushRecordEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("OA_BusinessFlowPushRecord", new string[] { "BusinessFlowModelCode", "ReferenceNo","RelatedReferenceNo", "IsPushed", "IsPushFailed", "IsClosed",
                "PushTime", "PushCount", "FailCount","PushFailRemark" }, new string[] { "BusinessFlowPushRecordId" });
            sql = string.Format("{0} {1} WHERE BusinessFlowPushRecordId=?BusinessFlowPushRecordId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowPushRecordId", entity.BusinessFlowPushRecordId, DbType.Int64, size: 20);
            parameters.Add("?BusinessFlowModelCode", entity.BusinessFlowModelCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ReferenceNo", entity.ReferenceNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?RelatedReferenceNo", entity.RelatedReferenceNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?IsPushed", entity.IsPushed, DbType.Boolean);
            parameters.Add("?IsPushFailed", entity.IsPushFailed, DbType.Boolean);
            parameters.Add("?IsClosed", entity.IsClosed, DbType.Boolean);
            parameters.Add("?PushTime", entity.PushTime, DbType.DateTime);
            parameters.Add("?PushCount", entity.PushCount, DbType.Int32, size: 11);
            parameters.Add("?FailCount", entity.FailCount, DbType.Int32, size: 11);
            parameters.Add("?PushFailRemark", entity.PushFailRemark?.Trim(), DbType.String);
            
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<BusinessFlowPushRecordEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<bool> Delete(long businessFlowPushRecordId)
        {
            string sql = @"DELETE FROM OA_BusinessFlowPushRecord WHERE BusinessFlowPushRecordId=?BusinessFlowPushRecordId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowPushRecordId", businessFlowPushRecordId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }

        public async Task<BusinessFlowPushRecordEntity> GetEntity(long businessFlowPushRecordId)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowPushRecordId=?BusinessFlowPushRecordId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowPushRecordId", businessFlowPushRecordId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<BusinessFlowPushRecordEntity>(sql, parameters);
        }

        public async Task<BusinessFlowPushRecordEntity> GetEntity(string businessFlowModelCode, string referenceNo)
        {
            string sql = string.Format("{0} WHERE BusinessFlowModelCode=?BusinessFlowModelCode AND ReferenceNo=?ReferenceNo AND IsPushed=0 AND IsClosed=0", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelCode", businessFlowModelCode?.Trim(), DbType.AnsiString);
            parameters.Add("?ReferenceNo", referenceNo?.Trim(), DbType.AnsiString);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<BusinessFlowPushRecordEntity>(sql, parameters);
        }

        public async Task<(IEnumerable<BusinessFlowPushRecordEntity>, int)> Query(string businessFlowModelCode, string referenceNo, DateTime? start, DateTime? end, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (!string.IsNullOrWhiteSpace(businessFlowModelCode))
            {
                wheres.Add("BusinessFlowModelCode=?BusinessFlowModelCode");
                parameters.Add("?BusinessFlowModelCode", businessFlowModelCode?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(referenceNo))
            {
                wheres.Add("ReferenceNo=?ReferenceNo");
                parameters.Add("?ReferenceNo", referenceNo?.Trim(), DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime DESC LIMIT {2},{3}; SELECT COUNT(1) FROM OA_BusinessFlowPushRecord {1}",
                   QUERY,
                   wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                   (pageIndex - 1) * pageSize,
                   pageSize);
            return await this.databaseContext.Slave.QueryPageableListAsync<BusinessFlowPushRecordEntity>(sql, parameters);
        }
    }
}
